package com.system.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BaseServlet extends HttpServlet
{
  private static final long serialVersionUID = -3965752461887180038L;
  protected final String NONE = null;

  public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
  {
    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;
    String page = doService(request, response);

    if (page != null)
      req.getRequestDispatcher(page).forward(req, res);
  }

  protected String doService(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
  {
    resp.setCharacterEncoding("GBK");
    String methodName = req.getParameter("method");
    String page = null;
    try {
      Class classType = getClass();
      Method method = classType.getDeclaredMethod(methodName, 
        new Class[] { HttpServletRequest.class, HttpServletResponse.class });
      page = (String)method.invoke(this, new Object[] { req, resp });
    } catch (Exception e) {
      e.printStackTrace();
      resp.sendRedirect("error.jsp");
    }
    return page;
  }

  protected void writeJsonReuslt(HttpServletResponse resp, String jsonStr)
    throws ServletException, IOException
  {
    resp.setContentType("text/json;charset=utf-8");
    resp.getWriter().write(jsonStr);
    resp.getWriter().flush();
  }

  protected void writeHtmlReuslt(HttpServletResponse resp, String html) throws ServletException, IOException
  {
    resp.setContentType("text/html;charset=utf-8");
    resp.getWriter().write(html);
    resp.getWriter().flush();
  }
}